import mongoose from 'mongoose'
mongoose.Promise = Promise
const ticketSchema = new mongoose.Schema({
  name: String,
  ticket: String,
  expires_in: Number,
  meta: {
    createdAt: {
      type: Date,
      default: Date.now()
    },
    updatedAt: {
      type: Date,
      default: Date.now()
    }
  }
})
ticketSchema.pre('save', function (next) {
  this.isNew ? this.meta.createdAt = this.meta.updatedAt = Date.now() : this.meta.updatedAt = Date.now()
  next()
})
ticketSchema.statics = {
  async getTicket() {
    const ticket = await this.findOne({
      name: 'ticket'
    }).exec()
    if (ticket && ticket.ticket) {
      ticket.ticket = ticket.ticket
    }
    return ticket
  },
  async saveTicket(data) {
    let ticket = await this.findOne({
      name: 'ticket'
    }).exec()
    if (ticket) {
      ticket.ticket = data.ticket
      ticket.expires_in = data.expires_in
    } else {
      ticket = new Ticket({
        name: 'ticket',
        ticket: data.ticket,
        expires_in: data.expires_in
      })
      await ticket.save()
    }
  },
  async rmTicket(data) {
    let ticket = await this.findOne({
      name: 'ticket'
    }).exec()
    let delState = ''
    if (ticket) {
      delState = await ticket.remove({
        name: 'ticket'
      }).exec()
    } else {
      delState = 'no accessticket alive'
    }
    return delState
  }
}
const Ticket = mongoose.model('Ticket', ticketSchema, 'Ticket')
export default Ticket
